﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BLToolkit.Data;

namespace Platform.Model
{
    /// <summary>
    /// Lop quan ly danh sach nha cung cap
    /// </summary>
    public class ProviderList
    {
        private List<Supplier> _providers;
        private Dictionary<string, Supplier> _mapper;

        /// <summary>
        /// Khoi tao doi tuong quan ly danh sach nha cung cap
        /// </summary>
        public ProviderList()
        {
        }

        /// <summary>
        /// Tai danh sach nha cung cap vao bo nho
        /// </summary>
        /// <param name="lastRefresh">Thoi diem tai du lieu gan nhat</param>
        public void Refresh(DateTime? lastRefresh = null)
        {
            if (lastRefresh == null)
            {
                // Lay danh sach nha cung cap
                _providers = Supplier.Objects.Where(x => x.MarketId == WorkSession.Current.Market.ID).ToList();
                // Tao tu dien de anh xa giua Supplier No va ID
                _mapper = _providers.ToDictionary(x => x.SupNo, x => x);
            }
            else
            {
                var suppliers = Supplier.Objects.Where(x => x.MarketId == WorkSession.Current.Market.ID
                                                         && x.LastUpdated > lastRefresh.Value).ToList();
                foreach (var prod in suppliers)
                {
                    if (_mapper.ContainsKey(prod.SupNo))
                        _mapper[prod.SupNo] = prod;
                    else
                        _mapper.Add(prod.SupNo, prod);
                }
                _providers = _mapper.Values.ToList();
            } // end if
        } // end method

        /// <summary>
        /// Lay nha cung cap theo ma so Supplier No
        /// </summary>
        /// <param name="supNo">Ma so cua nha cung cap</param>
        /// <returns>Tra ve nha cung cap co ma la supNo hoac null</returns>
        public Supplier GetProvider(string supNo)
        {
            return _mapper.ContainsKey(supNo) ? _mapper[supNo] : null;
        }

        /// <summary>
        /// Lay ID cua nha cung cap theo ma so Supplier No
        /// </summary>
        /// <param name="supNo">Ma so cua nha cung cap</param>
        /// <returns>Tra ve ID cua nha cung cap hoac bao loi neu khong tim thay</returns>
        public int GetProviderId(string supNo)
        {
            var provider = GetProvider(supNo);
            if (provider == null)
                throw new NullReferenceException("Khong tim thay nha cung cap co ma " + supNo);

            return provider.ID;
        }

        /// <summary>
        /// Lay danh sach cac nha cung cap
        /// </summary>
        /// <returns>Danh sach tat ca cac nha cung cap</returns>
        public List<Supplier> ToList()
        {
            return _providers;
        }

        public bool Delete(Supplier supp)
        {
            try
            {
                Supplier.Objects.DeleteById(supp.ID);
                _mapper.Remove(supp.SupNo);
                _providers.Remove(supp);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        public int AddOrUpdate(Supplier supp)
        {
            // Khong them duoc NCC moi do NCC da ton tai
            if (supp.ID == 0 && _mapper.ContainsKey(supp.SupNo))
                throw new DuplicateNameException("Cannot add new supplier with duplicate Sup_NO");

            // Them moi NCC
            if (supp.ID == 0)
            {
                supp.Insert();
                _mapper.Add(supp.SupNo, supp);
            }
            // truong hop cap nhat
            else
            {
                // Tim NCC da co trong danh sach theo id
                var supplier = _providers.FirstOrDefault(x => x.ID == supp.ID);

                // TRuong hop nhap ma moi nhung trung voi NCC khac
                if (supplier.SupNo != supplier.SupNo && _mapper.ContainsKey(supplier.SupNo))
                    throw new DuplicateNameException("Cannot update article with duplicate ART_NO");

                supp.Update();

                // Cap nhat gia tri moi cho NCC
                supplier.SupNo = supp.SupNo;
                supplier.FirstName = supp.FirstName;
                supplier.LastName = supp.LastName;
                supplier.Tel = supp.Tel;
                supplier.Address = supp.Address;
                supplier.LastUpdated = supp.LastUpdated;

                // Xoa thong tin NCC cu
                _mapper.Remove(supplier.SupNo);

                // thay doi bang NCC moi vua cap nhat
                _mapper.Add(supp.SupNo, supp);
            }

            return supp.ID;
        }

        public List<Supplier> SortByFirstName()
        {
            return _providers.OrderBy(p => p.FirstName).ToList();
        }
        public List<Supplier> SortByLastName()
        {
            return _providers.OrderBy(p => p.LastName).ToList();
        }
    }
}
